package dlut.alanhome.trafficview;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class snapshot {
	private String username;
	private String passwd;
	private String LoginAPI="http://appschallenge.juzz4.com/api/login";
	private String GetDevicesAPI="http://appschallenge.juzz4.com/api/device/search";
	private String GetSnapshotAPI="http://appschallenge.juzz4.com/api/snapshot";
	private String ControlAPI="http://appschallenge.juzz4.com/api/device/control";
	private String GAEIPSnapshotAPI="http://kai-video-treasfer.appspot.com/fetch?";
	private String GAESnapshotAPI="http://kai-video-treasfer.appspot.com/request?";
	private String GAEControlAPI="http://kai-video-treasfer.appspot.com/action?";
	private String mechanism="plain";
	private String sessionid;
	private String deviceinfo;
	private int zoom=0;
	private int h=1;
	private int v=1;
	JSONArray devices;
	Bitmap bm;
	
	void setusername(String name)
	{
		this.username = name;
	}
	void setpasswd(String pw)
	{
		this.passwd = pw;
	}
	int Login() throws ClientProtocolException, IOException, JSONException
	{
		HttpPost httppost = new HttpPost(LoginAPI);
		Map mps = new HashMap();
		mps.put("mechanism",mechanism);
		mps.put("password",passwd);
		mps.put("username",username);
		
		JSONObject json =new  JSONObject(mps);
		
		List<NameValuePair> args = new ArrayList <NameValuePair>();
		args.add(new BasicNameValuePair("data",json.toString()));
		httppost.setEntity(new UrlEncodedFormEntity(args,HTTP.UTF_8));
		HttpResponse httpresponse = new DefaultHttpClient().execute(httppost);
		
		int statuscode = httpresponse.getStatusLine().getStatusCode();
		if(statuscode == 200)
		{
			String result = EntityUtils.toString(httpresponse.getEntity());
			System.out.println(result);
			JSONObject resultdata = new JSONObject(result);
			this.sessionid = resultdata.getString("sessionid");
			System.out.println(sessionid);
		}
				
		return statuscode;
	}
	boolean Standardize() throws Exception
	{
		zoom=0;
		h=1;
		v=1;
		String strurl = this.GAEControlAPI;
		strurl += "zoom="+zoom+"&";
		strurl += "h="+h+"&";
		strurl += "v="+v;
			
		HttpGet httpget = new HttpGet(strurl);
		HttpResponse httpresponse = new DefaultHttpClient().execute(httpget);
		return true;
	}
	int Search() throws ClientProtocolException, IOException, JSONException
	{			
		Map mps = new HashMap();
		mps.put("sessionid",this.sessionid);
		
		JSONObject json =new  JSONObject(mps);
		
		String strurl =json.toString();
		System.out.println(strurl);
	    strurl = URLEncoder.encode(strurl,HTTP.UTF_8);
		System.out.println(strurl);
	    strurl = this.GetDevicesAPI+"?data="+strurl;
	    HttpGet httpget = new HttpGet(strurl);
	    
		//httpget.setHeader("Content-Type", "application/x-www-form-urlencoded");
		HttpResponse httpresponse = new DefaultHttpClient().execute(httpget);
		
		int statuscode = httpresponse.getStatusLine().getStatusCode();
		System.out.println("in search devices and status code is " + statuscode);
		if(statuscode == 200)
		{
			String result = EntityUtils.toString(httpresponse.getEntity());
			this.deviceinfo = result;
			System.out.println(result);
			JSONObject resultdata = new JSONObject(result);
			devices =  resultdata.getJSONArray("devices");
		
			System.out.println(	devices.length());
			String deviceid = ((JSONObject)devices.get(0)).getString("deviceid");
			System.out.println(deviceid);
		}
		return statuscode;
	}
	boolean zoomin() throws Exception
	{
		boolean flag=true;
		zoom++;
		if(zoom > 1){zoom=1;flag= false;}
		String strurl = this.GAEControlAPI;
		strurl += "zoom="+zoom+"&";
		strurl += "h="+h+"&";
		strurl += "v="+v;
			
		HttpGet httpget = new HttpGet(strurl);
		HttpResponse httpresponse = new DefaultHttpClient().execute(httpget);
		return flag;
	}
	boolean zoomout() throws Exception
	{
		boolean flag= true;
		zoom--;
		if(zoom<=0){h=1;v=1;}
		if(zoom < 0){zoom=0;flag= false;}
		String strurl = this.GAEControlAPI;
		strurl += "zoom="+zoom+"&";
		strurl += "h="+h+"&";
		strurl += "v="+v;
		
		HttpGet httpget = new HttpGet(strurl);
		HttpResponse httpresponse = new DefaultHttpClient().execute(httpget);
		return flag;
	}
	void up() throws Exception
	{
		v++;
		if(v > 2)v=2;
		String strurl = this.GAEControlAPI;
		strurl += "zoom="+zoom+"&";
		strurl += "h="+h+"&";
		strurl += "v="+v;
		
		HttpGet httpget = new HttpGet(strurl);
		HttpResponse httpresponse = new DefaultHttpClient().execute(httpget);
	}
	void down() throws Exception
	{
		v--;
		if(v < 0)v=0;
		String strurl = this.GAEControlAPI;
		strurl += "zoom="+zoom+"&";
		strurl += "h="+h+"&";
		strurl += "v="+v;
		
		HttpGet httpget = new HttpGet(strurl);
		HttpResponse httpresponse = new DefaultHttpClient().execute(httpget);
	}
	void left() throws Exception
	{
		h--;
		if(h < 0)h=0;
		String strurl = this.GAEControlAPI;
		strurl += "zoom="+zoom+"&";
		strurl += "h="+h+"&";
		strurl += "v="+v;
		
		HttpGet httpget = new HttpGet(strurl);
		HttpResponse httpresponse = new DefaultHttpClient().execute(httpget);
	}
	void right() throws Exception
	{
		h++;
		if(h > 2)h=2;
		String strurl = this.GAEControlAPI;
		strurl += "zoom="+zoom+"&";
		strurl += "h="+h+"&";
		strurl += "v="+v;
		
		HttpGet httpget = new HttpGet(strurl);
		HttpResponse httpresponse = new DefaultHttpClient().execute(httpget);
	}
	Bitmap getPic(int idx,String vurl, int height, int width,int usegae) throws Exception
	{    //use kaiyi video stream without gae
		if(usegae==0){
			Map mps = new HashMap();
			mps.put("sessionid",this.sessionid);
			//System.out.println("now get pic at device "+((JSONObject)devices.get(0)).getString("deviceid"));
			mps.put("deviceid",((JSONObject)devices.get(idx)).getString("deviceid"));
			
			JSONObject json =new  JSONObject(mps);
			
			String strurl = json.toString();
			System.out.println(strurl);
			strurl = URLEncoder.encode(strurl,"utf8");
			strurl= this.GetSnapshotAPI+"?data="+strurl;
		
			HttpGet httpget = new HttpGet(strurl);
			HttpResponse httpresponse = new DefaultHttpClient().execute(httpget);
		
			int statuscode = httpresponse.getStatusLine().getStatusCode();
			System.out.println("in search devices and status code is " + statuscode);
			if(statuscode == 200)
			{
				InputStream is = httpresponse.getEntity().getContent();
				bm = BitmapFactory.decodeStream(is);
				return bm;
				
			}
			else 
			{
				this.Login();
				return bm;
			}		
		}else if(usegae == 1) //use kaiyi video stream with gae
		{			
			String strurl = this.GAESnapshotAPI;
			strurl += "sid="+this.sessionid+"&";
			strurl += "did="+((JSONObject)devices.get(idx)).getString("deviceid")+"&";
			strurl += "width="+width+"&";
			strurl += "height="+height;
			System.out.println(strurl);
			HttpGet httpget = new HttpGet(strurl);
			HttpResponse httpresponse = new DefaultHttpClient().execute(httpget);
		
			int statuscode = httpresponse.getStatusLine().getStatusCode();
			System.out.println("in search devices and status code is " + statuscode);
			if(statuscode == 200)
			{
				InputStream is = httpresponse.getEntity().getContent();
				bm = BitmapFactory.decodeStream(is);
				return bm;
				
			}
			else 
			{
				this.Login();
				return bm;
			}		
		}
		else  // use gae and do not use kaiyi vdideo stream
		{
			/*String strurl = "http://"+vurl;
			HttpGet httpget = new HttpGet(strurl);
			HttpResponse httpresponse = new DefaultHttpClient().execute(httpget);
		
			int statuscode = httpresponse.getStatusLine().getStatusCode();
			System.out.println("in search devices and status code is " + statuscode);
			if(statuscode == 200)
			{
				InputStream is = httpresponse.getEntity().getContent();
				bm = BitmapFactory.decodeStream(is);
				return bm;
				
			}
			else 
			{
				this.Login();
				return bm;
			}	*/	
			
			
			String strurl = this.GAEIPSnapshotAPI;
			strurl += "url="+vurl+"&";			
			strurl += "width="+width+"&";
			strurl += "height="+height;
			System.out.println(strurl);
			HttpGet httpget = new HttpGet(strurl);
			HttpResponse httpresponse = new DefaultHttpClient().execute(httpget);
		
			int statuscode = httpresponse.getStatusLine().getStatusCode();
			System.out.println("in search devices and status code is " + statuscode);
			if(statuscode == 200)
			{
				InputStream is = httpresponse.getEntity().getContent();
				bm = BitmapFactory.decodeStream(is);
				return bm;
				
			}
			else 
			{
				this.Login();
				return bm;
			}		
			
		}
		
		
	}
	public static void main(String[] args) throws ClientProtocolException, IOException, JSONException
	{
		snapshot ss = new snapshot();
		ss.setusername("GoGeeks");
		ss.setpasswd("ace.dutss@gmail.com");
		ss.Login();
		ss.Search();
	}
		
}


